<?php 
namespace Common\Service\Sms;
/**
 * 106短信接口
 * @author liuyang
 *
 */    
use Common\ServiceInterface\SmsService;
use Common\Util\HttpUtil;
class  Sms106ServiceImpl implements SmsService { 
    //private $app_id = '182999800000039655';// 应用ID
    const APP_KEY = '94125044ef724060dee02b7c06fa98a3'; 
    const API_URL="http://apis.baidu.com/kingtto_media/106sms/106sms";
    private $timestamp=''; //时间戳，格式为：yyyy-MM-dd hh:mm:ss
    private $phone='';
    private $code; //验证码格式必须为6位的纯数字
    private $codelen = 6; //验证码长度必须为6位
    private $charset = "0123456789"; //验证码的随机因子
    private $exp_time=2; //验证码有效期长度，单位是分钟，可以为空，默认有效2分钟
    const SIGN="【xx】";
    
    /** 
     * (non-PHPdoc)
     * @see SmsService::sendInfo()
     * return int
     */
    public function sendInfo($phone,$content){  
        $this->phone=$phone;
        $this->createCode();
        $rand=0; 
        if($this->checkPhone($this->phone)){
            $rstval=$this->send($content);   
            if ($rstval['returnstatus']==="Success"){ //从发送短信的方法中返回的obj中读取发送成功与否的标识
                $rand=$this->getCode(); 
            } 
        } 
        return $rand;
    }
     
    
    //检查参数
    private function checkPhone($phone){
        if (preg_match('/^(1[0-9]{10})$/',$phone)){
            $this->phone=$phone;
            return true;
        }else{
            return false;
        }
    }
    //生成随机码
    private function createCode() {
        $_len = strlen($this->charset)-1;
        for ($i=0;$i<$this->codelen;$i++) {
            $this->code .= $this->charset[mt_rand(0,$_len)];
        }
    }
     
    //获取验证码
    private function getCode() {
        return $this->code;
    }
    
    private function FromXml($xml)
    { 
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $list= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);  
        return $list;
    }
    
    /**
     * send
     * @return Ambigous <boolean, mixed>
     */
    private function send($content) { 
        $content = str_replace("[code]", $this->code, $content);
        $header = array(
            'apikey: '.self::APP_KEY,
        ); 
        $param = array();
        $param[]="mobile=".$this->phone;
        $param[]= "content=".urlencode(self::SIGN.$content);
        $url=self::API_URL."?".implode("&", $param);   
        $obj=HttpUtil::curlGet($url,HttpUtil::DEFAULT_TIMEOUT,$header);  
        return $this->FromXml($obj);
    }
  
    
}